package com.itheima.sh.controller;

import com.itheima.sh.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    @HystrixCommand(fallbackMethod = "queryByIdFallBack")
    public User queryById(@PathVariable("id") String id) {
        // 定义请求的url
//        String url = "http://localhost:8081/user/" + id;
//        // 调用RestTemplate的getForObject方法，指定url地址和返回值类型
//        Map map = restTemplate.getForObject(url, Map.class);

        // 基于 Eureka 调用
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        ServiceInstance serviceInstance = instances.get(0);
//        String host = serviceInstance.getHost();
//        int port = serviceInstance.getPort();
//        String url = serviceInstance.getUri().toString();
//
//        System.out.println("url = " + url);
//        String urlConn="http://"+host+":"+port+"/user/"+id;
//        Map userMap = restTemplate.getForObject(urlConn, Map.class);

        //Ribbon负载均衡

//        try {
//            Thread.sleep(3000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        String url = "http://user-service/user/" + id;

        if ("itheima".equals(id)){
            throw new RuntimeException("itheima");
        }

        User user = restTemplate.getForObject(url, User.class);

        return user;
    }

    // 降级方法
    public User queryByIdFallBack(String id) {
        User user = new User();
        user.setUsername(id);
        user.setName("暂停服务");
        return user;
    }

}
